<?php
# ***** BEGIN LICENSE BLOCK *****
# This file is part of "myWiWall".
# Copyright (c) 2007-2008 CRP Henri Tudor and contributors.
# All rights reserved.
#
# "myWiWall" is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
# 
# "myWiWall" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with "myWiWall"; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# ***** END LICENSE BLOCK *****


/**
 * The Auth class provides services as static methods providing you features related
 * to the state of the current user on the system such as login, logout, security ...
 *
 * @author Laurent Haan <laurent.haan@gmail.com>
 * @author J�r�me Bogaerts <jerome.bogaerts@gmail.com>
 * @package mywiwall.util
 */
class Auth
{
	/**
	 * Sets the current user-agent as "authenticated" if the provided
	 * username and password are matching its account in database.
	 * 
	 * After a successful invokation of this method, the state of the user
	 * remain persistant in the session so that you can use the other methods
	 * of this class to know more about the state of the user in the system e.g
	 * if he's authenticated, what is its user level, ...
	 *
	 * @param string $username The username of the user to authenticate.
	 * @param string $password The password in clear (the method is in charge of encoding).
	 */
	public static function login($username, $password)
	{
		Auth::logout(false);
		
		// Database Connection.
		$db = DbUtil::accessFactory();
		
		// Sanitization.
		$username = $db->escape($username);
		$password = md5($db->escape($password));
		
		$rs = $db->select("SELECT id, level, username, copname FROM users WHERE username = '" . $username . "' AND password = '" . $password . "'");
		
		// Check if a result was found.
		if($rs->count())
		{
			$_SESSION['authenticated'] = true;
			$_SESSION['userid'] = $rs->id;
			$_SESSION['level'] = $rs->level;
			$_SESSION['username'] = $rs->username;
			$_SESSION['copname'] = $rs->copname;
		}
	}
	
	/**
	 * Sets the current user-agent as "authenticated" if the provided
	 * openid is matching its account in database.
	 * 
	 * After a successful invokation of this method, the state of the user
	 * remain persistant in the session so that you can use the other methods
	 * of this class to know more about the state of the user in the system e.g
	 * if he's authenticated, what is its user level, ...
	 *
	 * @param string $openid The OpenId .
	 * @param string $password The password in clear (the method is in charge of encoding).
	 */
	public static function loginByOpenid($openid)
	{
		Auth::logout(false);
		
		// Database Connection.
		$db = DbUtil::accessFactory();
		
		// Sanitization.
		$openid = $db->escape($openid);
		
		$rs = $db->select("SELECT id, level, username FROM users WHERE openid = '" . $openid . "'");
		
		// Check if a result was found.
		if($rs->count())
		{
			$_SESSION['authenticated'] = true;
			$_SESSION['userid'] = $rs->id;
			$_SESSION['level'] = $rs->level;
			$_SESSION['username'] = $rs->username;
			$_SESSION['copname'] = $rs->copname;
		}
	}
	
	/**
	 * Logsout the user. After invoking this method, user will be automatically
	 * redirect to the login page if he attempts to reach the website again.
	 *
	 */
	public static function logout($destroy = true)
	{
		unset($_SESSION['userid']);
		unset($_SESSION['authenticated']);
		unset($_SESSION['level']);
		unset($_SESSION['username']);
		
		if ($destroy)
		{			
			session_unset();
			session_destroy();
		}
	}
	
	/**
	 * Indicates if the current user is authenticated on the system or not.
	 *
	 * @return bool Returns true if the user is authenticated, false if not.
	 */
	public static function isAuth()
	{
		return isset($_SESSION['authenticated']) && $_SESSION['authenticated'];
	}
	
	/**
	 * Indicates if the current user is authenticated and has an 'administrator' profile
	 * (level 1 in database).
	 *
	 * @return bool If the current user is authenticated and has an 'administrator' profile.
	 */
	public static function isAdmin()
	{
		global $levels;
		return isset($_SESSION['level']) && ($_SESSION['level'] == $levels['admin']);
	}
	
	/**
	 * Indicates if the current user is authenticated and has a 'superadmin' profile (level 2
	 * in database).
	 *
	 * @return bool If the current user is authenticated and has a 'superadmin' profile.
	 */
	public static function isGod()
	{
		global $levels;
		return isset($_SESSION['level']) && ($_SESSION['level'] == $levels['superadmin']);
	}
	
	/**
	 * Obtains the current user id (numeric identifier from Database) if he is logged in.
	 *
	 * @return integer The user database identifier.
	 */
	public static function getUserId()
	{
		if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'] == true)
			return $_SESSION['userid'];
		else
			throw new AuthException(MwwException::MODEL, 'Trying to get user id when user not yet authenticated');
	}
	
	/**
	 * Obtains the username of the current user if he is logged in.
	 *
	 * @return string The user's username.
	 */
	public static function getUserName()
	{
		if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'] == true)
			return $_SESSION['username'];
		else
			throw new AuthException(MwwException::MODEL, 'Trying to get user name when user not yet authenticated');
	}
	
	/**
	 * Obtains the user level of the current user if he is logged in.
	 *
	 * @return string the user level ('admin', 'superadmin' or 'user').
	 * FIXME Throw an exception when the user is not logged in !
	 */
	public static function getUserLevel()
	{
		if (self::isAdmin())
			return 'admin';
			
		else if (self::isGod())
			return 'superadmin';
			
		else if (self::isAuth())
			return 'user';
			
		else
			throw new AuthException(MwwException::MODEL, 'Trying to get user level when user not yet authenticated');
	}
	
	public static function getCopName()
	{
		if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'] == true)
			return $_SESSION['copname'];
		else
			throw new AuthException(MwwException::MODEL, 'Trying to get copname of the user when not yet authenticated');
	}
	
	public static function getLanguage()
	{
		if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'] == true)
		{
			$userId = $_SESSION['userid'];
			
			$db = DbUtil::accessFactory();
			$rs = $db->select("SELECT lang FROM users WHERE id = ${userId}");
			
			return $rs->lang;
		}
		else
			throw new AuthException(MwwException::MODEL, 'Trying to get the language of the user when not yet authenticated');
	}
	
	public static function getOpenId()
	{
		if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'] == true)
		{
			$userId = $_SESSION['userid'];
			
			$db = DbUtil::accessFactory();
			$rs = $db->select("SELECT openid FROM users WHERE id = ${userId}");
			
			return $rs->openid;
		}
		else
			throw new AuthException(MwwException::MODEL, 'Trying to get the openid of the user when not yet authenticated');
	}
}
?>